<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML创建工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }
        textarea {
            width: 100%;
            height: 300px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            font-family: Consolas, monospace;
            margin-bottom: 15px;
        }
        input[type="text"] {
            width: calc(100% - 120px);
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 15px;
            display: inline-block;
        }
        .button-container {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        button#generateBtn {
            background-color: #2196F3;
            margin-left: 10px;
        }
        button#generateBtn:hover {
            background-color: #0b7dda;
        }
        button#validateBtn {
            background-color: #FF9800;
        }
        button#validateBtn:hover {
            background-color: #e68a00;
        }
        button#previewBtn {
            background-color: #9C27B0;
        }
        button#previewBtn:hover {
            background-color: #7B1FA2;
        }
        .message {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            border: 1px solid #d6e9c6;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
            border: 1px solid #ebccd1;
        }
        .warning {
            background-color: #fcf8e3;
            color: #8a6d3b;
            border: 1px solid #faebcc;
        }
        .external-tools {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
            text-align: center;
        }
        .external-tools a {
            display: inline-block;
            background-color: #6c5ce7;
            color: white;
            padding: 10px 15px;
            text-decoration: none;
            border-radius: 4px;
            font-weight: bold;
            margin: 0 10px;
            transition: background-color 0.3s;
        }
        .external-tools a:hover {
            background-color: #5541d7;
        }
        .tool-description {
            margin-top: 10px;
            color: #666;
            font-size: 14px;
        }
        
        /* 预览框样式 */
        .preview-container {
            margin-top: 20px;
            display: none;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        .preview-header {
            background-color: #f5f5f5;
            padding: 10px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
        }
        .preview-title {
            font-weight: bold;
            color: #333;
        }
        .preview-close {
            cursor: pointer;
            color: #999;
            font-weight: bold;
        }
        .preview-close:hover {
            color: #333;
        }
        .preview-frame {
            width: 100%;
            height: 400px;
            border: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>HTML页面生成工具</h1>
        
        <div>
            <label for="htmlContent">HTML内容：</label>
            <textarea id="htmlContent" placeholder="请输入HTML代码..."></textarea>
        </div>
        
        <div>
            <label for="fileName">文件名（可选）：</label>
            <input type="text" id="fileName" placeholder="不填则自动生成随机文件名">
            <button id="generateBtn" title="生成随机文件名">随机生成</button>
        </div>
        
        <div class="button-container">
            <button id="createBtn">保存HTML到static</button>
            <button id="validateBtn">验证HTML</button>
            <button id="previewBtn">预览HTML</button>
        </div>
        
        <div id="message" class="message"></div>
        
        <!-- 预览容器 -->
        <div id="previewContainer" class="preview-container">
            <div class="preview-header">
                <span class="preview-title">HTML预览</span>
                <span class="preview-close" onclick="closePreview()">✕</span>
            </div>
            <iframe id="previewFrame" class="preview-frame"></iframe>
        </div>
        
        <div class="external-tools">
            <h3>外部HTML生成工具</h3>
            <a href="https://huggingface.co/spaces/victor/deepsite" target="_blank">deepsite生成html</a>
            <p class="tool-description">DeepSite是一个AI驱动的工具，可以通过描述生成完整的HTML网页。试试用它来生成HTML内容，然后粘贴到这里！</p>
        </div>
    </div>

    <script>
        document.getElementById('generateBtn').addEventListener('click', function() {
            // 生成随机文件名
            const randomStr = 'html_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
            document.getElementById('fileName').value = randomStr;
        });
        
        document.getElementById('createBtn').addEventListener('click', async function() {
            const htmlContent = document.getElementById('htmlContent').value.trim();
            let fileName = document.getElementById('fileName').value.trim();
            
            // 验证输入
            if (!htmlContent) {
                showMessage('请输入HTML内容', 'error');
                return;
            }
            
            // 验证HTML内容
            if (!isValidHTML(htmlContent)) {
                showMessage('请输入有效的HTML内容（必须包含基本的HTML标记）', 'error');
                return;
            }
            
            // 如果未提供文件名，生成随机文件名
            if (!fileName) {
                fileName = 'html_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
            }
            
            // 确保文件名有.html后缀
            if (!fileName.endsWith('.html')) {
                fileName += '.html';
            }
            
            try {
                const response = await fetch('/text2html/create_html', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        content: htmlContent,
                        filename: fileName
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    if (data.file_exists) {
                        showMessage(`文件名 ${data.original_filename} 已存在！已自动重命名为 ${data.filename}`, 'warning');
                    } else {
                        showMessage(`HTML页面创建成功！文件名: ${data.filename}`, 'success');
                    }
                    // 可选: 清空输入
                    document.getElementById('htmlContent').value = '';
                    document.getElementById('fileName').value = '';
                } else {
                    showMessage(`创建失败: ${data.detail || '未知错误'}`, 'error');
                }
            } catch (error) {
                showMessage(`请求错误: ${error.message}`, 'error');
            }
        });
        
        function isValidHTML(content) {
            // 简单检查是否包含基本的HTML标签
            const hasHTMLTags = /<html.*?>.*?<\/html>/is.test(content);
            const hasBodyTags = /<body.*?>.*?<\/body>/is.test(content);
            const hasHeadTags = /<head.*?>.*?<\/head>/is.test(content);
            
            // 至少包含以上三个基本标签之一
            return hasHTMLTags || hasBodyTags || hasHeadTags;
        }
        
        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type}`;
            messageEl.style.display = 'block';
            
            // 5秒后自动隐藏成功消息
            if (type === 'success') {
                setTimeout(() => {
                    messageEl.style.display = 'none';
                }, 5000);
            }
        }
        
        // 验证HTML按钮点击事件
        document.getElementById('validateBtn').addEventListener('click', function() {
            const htmlContent = document.getElementById('htmlContent').value.trim();
            
            if (!htmlContent) {
                showMessage('请输入HTML内容再验证', 'error');
                return;
            }
            
            // 进行更详细的HTML验证
            const validationResult = validateHTML(htmlContent);
            
            if (validationResult.valid) {
                showMessage('HTML格式验证通过！', 'success');
            } else {
                showMessage(`HTML验证失败: ${validationResult.error}`, 'error');
            }
        });
        
        // 详细的HTML验证
        function validateHTML(content) {
            try {
                // 创建一个新的DOMParser
                const parser = new DOMParser();
                // 尝试解析HTML内容
                const doc = parser.parseFromString(content, 'text/html');
                
                // 检查是否有解析错误
                const parseError = doc.querySelector('parsererror');
                if (parseError) {
                    return { valid: false, error: '解析错误，HTML结构有问题' };
                }
                
                // 检查基本结构
                if (!doc.documentElement) {
                    return { valid: false, error: '缺少根元素' };
                }
                
                // 检查必要的标签
                const hasHTMLTag = doc.querySelector('html');
                const hasHeadTag = doc.querySelector('head');
                const hasBodyTag = doc.querySelector('body');
                
                if (!hasHTMLTag) {
                    return { valid: false, error: '缺少<html>标签' };
                }
                
                if (!hasHeadTag) {
                    return { valid: false, error: '缺少<head>标签' };
                }
                
                if (!hasBodyTag) {
                    return { valid: false, error: '缺少<body>标签' };
                }
                
                // 检查DOCTYPE声明
                if (!content.toLowerCase().includes('<!doctype html>') && 
                    !content.toLowerCase().includes('<!DOCTYPE html>')) {
                    return { valid: true, error: '警告：缺少DOCTYPE声明，建议添加<!DOCTYPE html>' };
                }
                
                return { valid: true };
            } catch (e) {
                return { valid: false, error: `验证过程出错: ${e.message}` };
            }
        }
        
        // 预览HTML按钮点击事件
        document.getElementById('previewBtn').addEventListener('click', function() {
            const htmlContent = document.getElementById('htmlContent').value.trim();
            
            if (!htmlContent) {
                showMessage('请输入HTML内容再预览', 'error');
                return;
            }
            
            // 显示预览框
            const previewContainer = document.getElementById('previewContainer');
            previewContainer.style.display = 'block';
            
            // 获取iframe
            const previewFrame = document.getElementById('previewFrame');
            
            // 写入HTML内容
            const frameDoc = previewFrame.contentDocument || previewFrame.contentWindow.document;
            frameDoc.open();
            frameDoc.write(htmlContent);
            frameDoc.close();
        });
        
        // 关闭预览
        function closePreview() {
            document.getElementById('previewContainer').style.display = 'none';
        }
    </script>
</body>
</html>
